package com.wistech.search.solr.score;

import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.greenpineyu.fel.Expression;
import com.greenpineyu.fel.FelEngine;
import com.greenpineyu.fel.FelEngineImpl;
import com.greenpineyu.fel.context.FelContext;
import com.greenpineyu.fel.context.MapContext;
import com.wistech.search.solr.extend.model.Company;
import com.wistech.utils.ExpressionUtils;

/**
 * 基于 Fast-el表达式引擎实现的评分表达式
 * 
 * @author Liuye
 * 
 */
public class FelScoreExpression implements ScoreExpression {
	private static Logger log = LoggerFactory
			.getLogger(FelScoreExpression.class);

	private Expression expression;// 表达式对象
	private List<String> vars;// 表达式变量

	public FelScoreExpression(String expressionString) {
		this.vars = ExpressionUtils.getVars(expressionString);
		FelEngine felEngine = new FelEngineImpl();
		this.expression = felEngine.compile(expressionString,
				getDefaultValues());
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.wistech.search.solr.score.ScoreExpression#eval(java.util.Map)
	 */
	@Override
	public float eval(Map<String, Object> model) {
		FelContext env = getDefaultValues();
		if (model != null) {
			for (Map.Entry<String, Object> entry : model.entrySet()) {
				env.set(entry.getKey(), entry.getValue());
			}
			try {
				Object result = expression.eval(env);
				if (result instanceof Float) {
					return (Float) result;
				} else if (result instanceof Number) {
					return ((Number) result).floatValue();
				} else {
					return Float.parseFloat(result.toString());
				}
			} catch (RuntimeException e) {
				log.error("run score() method error.", e);
				return 0f;
			}
		}
		return 0f;
	}

	public FelContext getDefaultValues() {
		FelContext ctx = new MapContext();
		for (String var : vars) {
			ctx.set(var, 0f);
		}
		Company company = new Company();
		ctx.set("c", company);
		return ctx;
	}
}
